<template>
  <page-header-wrapper :title="false">
    <a-card
      title="文章列表"
    >
      <template slot="extra">
        <a-button size="small" icon="upload" style="margin-right: 5px" type="danger" @click="onImport">批量上传文章</a-button>
        <a-button size="small" icon="plus" type="danger" @click="addList">添加文章</a-button>
<!--        <a-button type="danger" @click="delList" style="margin-left: 20px">批量删除</a-button>-->
      </template>
      <div class="table-page-search-wrapper">
        <a-form-model
          layout="inline"
          :model="queryParam"
        >
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="一级分类">
                <a-select v-model="queryParam['filter[parent_category_name]']" placeholder="请选择一级分类" @change="onChangeFirst">
                  <a-select-option v-for="(item, index) in firstOpts" :key="index" :value="item.id">{{item.title}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="二级分类">
                <a-select v-model="queryParam['filter[category_name]']" placeholder="请选择二级分类" @change="onChangeSecond">
                  <a-select-option v-for="(item, index) in secondOpts" :key="index" :value="item.id">{{item.title}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
                <span class='table-page-search-submitButtons' >
                  <a-button type="primary" @click="searchBtn">搜索</a-button>
                  <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div class="table-operator">
        <s-table
          bordered
          ref="table"
          size="middle"
          :row-key="(record) => record.id"
          :columns="listColumns"
          :data="listData"
        >
          <template slot="cover" slot-scope="text">
            <img :src="text" style="width: 25px"  @click="lookImg(text)"/>
          </template>
          <template slot="status" slot-scope="text">
            <a-tag v-if="text == 1" color="blue">显示</a-tag>
            <a-tag v-else color="red">隐藏</a-tag>
          </template>
          <template slot="action" slot-scope="text, record">
            <a-button size="small" type="primary" @click="editList(record.id)">编辑</a-button>
            <a-button size="small" type="danger" @click="delList(record.id)">删除</a-button>
          </template>
        </s-table>
      </div>
    </a-card>
    <a-modal
      title="批量上传文章CSV"
      v-model="importVisible"
      :confirm-loading="uploadLoading"
      @ok="onSubmit"
    >
      <a-form-model
        ref="uploadForm"
        :model="uploadForm"
        :rules="uploadRules"
      >
        <a-form-model-item label="上传CSV文件" prop="value">
          <a-upload
            name="file"
            accept=".csv"
            :multiple="true"
            :action="uploadUrl"
            :headers="headers"
            @change="handleChange"
          >
            <a-button> <a-icon type="upload" /> 上传CSV </a-button>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item label="选择要发布的公司" prop="company">
          <a-checkbox-group v-model="uploadForm.company">
            <a-checkbox v-for="(item,index) in companyOpts" :key="index" :value="index">
              {{item}}
            </a-checkbox>
          </a-checkbox-group>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
  import { STable } from '@/components'
  import articleColumns from '@/columns/common.article'
  import { getArticleListDel, getArticleList, postImportArticle, getImportArticle, getArticleCat, getArticleCats } from '@/api/article'
  import storage from 'store'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import apis from '@/api'

  export default {
    components: {
      STable
    },
    name: 'ArticleList',
    data () {
      return {
        listColumns: articleColumns.list,
        listData: parameters => {
          return getArticleList(Object.assign(parameters, this.queryParam)).then(res => {
            return res.result
          })
        },
        selectedRowKeys: [],
        queryParam: {},
        importVisible: false,
        uploadForm: {
          filename: '',
          value: '',
          company: []
        },
        uploadRules: {
          value: [{ required: true, message: '请上传CSV文件', trigger: 'blur' }],
          company: [{ type: 'array', required: true, message: '必须选择上传至某个公司', trigger: 'change' }]
        },
        headers: { 'Access-Token': storage.get(ACCESS_TOKEN) },
        uploadUrl: apis.UploadFile,
        uploadLoading: false,
        companyOpts: {},
        firstOpts: {},
        secondOpts: {}
      }
    },
    activated () {
      this.$refs.table.refresh()
    },
    created () {
      getArticleCat().then(res => {
        this.firstOpts = res.result.data
      })
    },
    methods: {
      onSelectChange (selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },
      lookImg (src) {
        window.open(src)
      },
      addList () {
        this.$router.push({ name: 'addList' })
      },
      onImport () {
        getImportArticle().then(res => {
          this.companyOpts = res.result.companyOpts
          this.importVisible = true
        })
      },
      onSubmit () {
        const app = this
        const data = {}
        app.$refs.uploadForm.validate(valid => {
          if (valid) {
            app.uploadLoading = true
            data['file[filename]'] = app.uploadForm.filename
            data['file[value]'] = app.uploadForm.value
            data['company'] = app.uploadForm.company
            postImportArticle(data).then(res => {
              if (res.status === 0) {
                app.importVisible = false
                app.uploadLoading = false
                app.$refs.table.refresh(true)
              } else {
                app.$warning({
                  title: res.msg
                })
                app.uploadLoading = false
              }
            })
          } else {
            return false
          }
        })
      },
      editList (id) {
        this.$router.push({ name: 'editList', params: { id } })
      },
      handleChange (info) {
        console.log(info)
        if (info.file.status === 'uploading') {
          this.uploadLoading = true
        }
        if (info.file.status === 'done') {
          this.uploadForm.value = info.file.response.result.url
          this.uploadForm.filename = info.file.name
          this.uploadLoading = false
        }
      },
      delList (id) {
        const app = this
        const arr = []
        arr[0] = id
        // if (id !== '') {
        //   arr[0] = id
        // } else {
        //   for (const k in app.selectedRowKeys) {
        //     arr[k] = app.selectedRowKeys[k]
        //   }
        // }
        app.$confirm({
          title: '确定删除选中的文章吗？',
          onOk: () => {
            getArticleListDel(arr).then(res => {
              if (res.status === 0) {
                app.$message.success('删除成功')
                this.$refs.table.refresh(true)
              } else {
                app.$warning({
                  title: res.msg
                })
              }
            })
          }
        })
      },
      reset () {
        this.queryParam = {}
        this.secondOpts = {}
        this.firstId = ''
        this.secondId = ''
        this.$refs.table.refresh(true)
      },
      onChangeFirst (id) {
        this.secondOpts = {}
        this.firstId = id
        this.secondId = ''
        getArticleCats(id).then(res => {
          this.secondOpts = res.result.data
        })
      },
      onChangeSecond (id) {
        this.secondId = id
      },
      searchBtn () {
        if (this.secondId === '') {
          this.queryParam['filter[category_id]'] = this.firstId
        } else {
          this.queryParam['filter[category_id]'] = this.secondId
        }
        this.$refs.table.refresh(true)
      }
    }
  }
</script>

<style scoped>
</style>
